package com.yhn.init.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhn.init.common.ErrorCode;
import com.yhn.init.constant.CommonConstant;
import com.yhn.init.constant.FileConstant;
import com.yhn.init.exception.BusinessException;
import com.yhn.init.mapper.UserMapper;
import com.yhn.init.model.dto.user.UserLoginRequest;
import com.yhn.init.model.dto.user.UserQueryRequest;
import com.yhn.init.model.dto.user.UserRegisterRequest;
import com.yhn.init.model.dto.user.UserUpdatePasswordRequest;
import com.yhn.init.model.entity.User;
import com.yhn.init.model.enums.UserRoleEnum;
import com.yhn.init.model.vo.LoginUserVO;
import com.yhn.init.model.vo.UserVO;
import com.yhn.init.service.FileService;
import com.yhn.init.service.UserService;
import com.yhn.init.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.yhn.init.constant.UserConstant.USER_LOGIN_STATE;


/**
 * @author yhn
 * @version 1.0
 * @description 用户服务实现
 * @date 2024/1/25 12:53
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private FileService fileService;

    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "yhn";


    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {

        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // 通过 synchronized 代码块可以确保：
        // 1. 在检查账号是否已存在（即调用 selectCount 查询数据库前）和插入新用户记录之间不会有其他线程对同一个账号进行操作。
        // 2. 避免了因并发导致的多次插入相同账号
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_account", userAccount);
            long count = baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }


    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        LoginUserVO loginUserVO = getLoginUserVO(user);
        Long userId = loginUserVO.getId();
        if (userId != null) {
            /*
             * 实现同端互斥效果，把该用户Web端的令牌销毁。
             * 在其他浏览器上已经登陆的该账户，令牌就失效了，实现同端互斥。
             */
            StpUtil.logout(userId);
            //通过会话对象，向SaToken传递userId
            StpUtil.login(userId);

            loginUserVO.setPermission(StpUtil.getPermissionList());
            loginUserVO.setToken(String.valueOf(StpUtil.getTokenInfo().tokenValue));
            // 将 VO 对象存储到会话中
            StpUtil.getSession().set("loginUserVO", loginUserVO);
        }
        return loginUserVO;
    }

    /**
     * 修改密码
     *
     * @param userUpdatePasswordRequest 修改密码请求
     * @return 是否修改成功【1-成功，0-失败】
     */
    @Override
    public int updatePassword(UserUpdatePasswordRequest userUpdatePasswordRequest) {
        LoginUserVO loginUser = getLoginUser();
        if (userUpdatePasswordRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userUpdatePasswordRequest.getUserAccount();
        String userPassword = userUpdatePasswordRequest.getUserPassword();
        String newUserPassword = userUpdatePasswordRequest.getNewUserPassword();
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, newUserPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码过短");
        }
        if (newUserPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新输入的密码过短");
        }
        if (userPassword.equals(newUserPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码一致");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        userPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        queryWrapper.eq("user_password", userPassword);
        Long num = baseMapper.selectCount(queryWrapper);
        if (num == 0 || !loginUser.getUserAccount().equals(userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "输入的用户名密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + newUserPassword).getBytes());
        // 3. 插入数据
        User updateUser = new User();
        updateUser.setUserPassword(encryptPassword);
        updateUser.setId(loginUser.getId());
        return baseMapper.updateById(updateUser);
    }


    @Override
    public LoginUserVO userLoginByMpOpen(WxOAuth2UserInfo wxOAuth2UserInfo, HttpServletRequest request) {
        String unionId = wxOAuth2UserInfo.getUnionId();

        // 单机锁
        synchronized (unionId.intern()) {
            // 查询用户是否已存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("union_id", unionId);
            User user = this.getOne(queryWrapper);
            // 被封号，禁止登录
//            if (user != null && UserRoleEnum.BAN.getValue().equals(user.getUserRole())) {
//                throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "该用户已被封，禁止登录");
//            }
            // 用户不存在则创建
            if (user == null) {
                user = new User();
                user.setUserAvatar(wxOAuth2UserInfo.getHeadImgUrl());
                user.setUserName(wxOAuth2UserInfo.getNickname());
                boolean result = this.save(user);
                if (!result) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败");
                }
            }
            // 记录用户的登录态
            request.getSession().setAttribute(USER_LOGIN_STATE, user);
            return getLoginUserVO(user);
        }
    }

    /**
     * 通过StpUtil的session获取当前的登录对象
     *
     * @return 当前登录对象
     */
    @Override
    public LoginUserVO getLoginUser() {
        return (LoginUserVO) StpUtil.getSession().get("loginUserVO");
    }


    /**
     * 获取当前登录用户（允许未登录）
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUserPermitNull(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            return null;
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        return this.getById(userId);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return isAdmin(user);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getRoleId());
    }

    /**
     * 用户注销
     */
    @Override
    public boolean userLogout() {
        // 从令牌中解密出来userId
        Long userId = StpUtil.getLoginIdAsLong();
        // 销毁令牌
        StpUtil.logout(userId);
        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        Integer userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        Integer gender = userQueryRequest.getGender();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(gender != null, "gender", gender);
//        queryWrapper.eq(StringUtils.isNotBlank(userRole), "userRole", userRole);
//        queryWrapper.like(StringUtils.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.like(StringUtils.isNotBlank(userName), "user_name", userName);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public String uploadImage(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
        LoginUserVO loginUser = this.getLoginUser();
        Long userId = loginUser.getId();
        User user = new User();
        user.setId(userId);
        try {
            // 生成新的文件名
            String uploadedImage = fileService.uploadImage(file, FileConstant.FILE_UPLOAD_PATH_IMG);
            user.setUserAvatar(uploadedImage);
            baseMapper.updateById(user);
            return uploadedImage;
        } catch (Exception e) {
            // 捕获上传过程中可能抛出的异常
            // 这里可以根据不同的异常类型进行不同的处理
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败，请重试");
        }
    }
}
